package com.atguigu.gmall.seckill.listener;

import com.atguigu.gmall.seckill.service.SeckillOrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * projectName: gmall
 *
 * @author: 陈鹏
 * time: 2022/10/18 21:08 星期二
 * description: 监听超时订单消息
 */
@Component
@Log4j2
public class SeckillOrderTimeoutListener {

    @Autowired
    private SeckillOrderService seckillOrderService;

    /**
     * 取消超时未支付的订单
     * @param channel
     * @param message
     */
    @RabbitListener(queues = "seckill_order_delay_normal_queue")
    public void seckillOrderTimeout(Channel channel, Message message){
        //获取消息的属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息的编号
        long deliveryTag = messageProperties.getDeliveryTag();
        //获取排队信息
        String username = new String(message.getBody());
        try {
            //超时取消订单
            seckillOrderService.cancelSeckillOrder(username);
            //确认消息
            channel.basicAck(deliveryTag, false);
        }catch (Exception e){
            try {
                //拒绝过保存到日志,消息拒绝消费并丢弃
                log.error("秒杀订单超时取消失败,原因为:" + e.getMessage());
                log.error("秒杀订单超时取消失败,失败的用户为:" + username);
                channel.basicReject(deliveryTag, false);
            }catch (Exception e1){
                log.error("秒杀订单超时取消失败,原因为:" + e.getMessage());
                log.error("秒杀订单超时取消失败,失败的用户为:" + username);
            }
        }
    }
}
